;loader1 is in 0th cyl; loader2 starts from chs=41h
%include "nasm_macros.inc"
%include "os.inc"
BITS 16
section .text 
org 100h
start:
cld
call disk_reset
mov eax,LOADER_SZ
test eax,SECT_SZ - 1
je x1
add eax,SECT_SZ
x1:
shr eax,SECT_SHIFT
mov [nsct_ldr],eax
call disk_info
mov dx,msg5
jc near exit
;write our mbr; skip for real disk 
mov edx,DISK_FLOPPY
mov eax,mbr_start
mov ebx,MBR_CHS   ;00HHCCCS;
mov ecx,SECT_SZ
xor si,si
call write_disk
mov dx,msg6
jc near exit
;
mov edx,DISK_FLOPPY
mov eax,buf
mov ebx,1   ;00HHCCCS;
mov ecx,SECT_SZ
xor si,si
call read_disk
mov dx,msg1
jc near exit
xor ecx,ecx
cmp word [buf+1feh],MBR_MAGIC
mov edx,msg3
jne near exit
mov cl,4
mov esi,buf + PRT_START
xor ebx,ebx
xor edx,edx ;# of new | old
lo1:
lodsd
test al,80h ; active part?
je jok
inc ebx
test dl,80h
jne jnx
mov al,4
sub al,cl
mov dl,al
or dl,80h
jmp jnx
jok:
test dh,80h
jne jnx
mov al,4
sub al,cl
mov dh,al
or dh,80h
jnx:
add esi,16-4
loop lo1
mov eax,edx
mov dx,msg4
and ax,7f7fh
cmp bl,1
ja near exit
je je1
mov ax,0ffffh
je1:
mov word [ldr_start + 1],ax
;
or ax,ax
js js1
push ax
and ax,0ffh
shl eax,4 ; *16
add eax,buf + SECT_SZ - 2 -4*4*4
mov byte [eax],0
;write loader to sec 2
pop ax
js1:
or ax,ax
jns jns1
xor ax,ax
jns1:
mov al,ah
and ax,0ffh
shl eax,4 ; *16
add eax,buf + SECT_SZ - 2 -4*4*4
mov ecx,LOADER_SZ
mov ebx,LOADER_CHS
call init_ptable
mov edx,DISK_FLOPPY
mov eax,buf
mov ebx,MBR_CHS   ;00HHCCCS;
mov ecx,SECT_SZ
xor si,si
call write_disk
mov dx,msg6
jc exit
mov dword [ldr_start + LOADER_SZ - MAX_CHSINTS_SZ- 8],LOADER2_CHS
mov dword [ldr_start + LOADER_SZ - MAX_CHSINTS_SZ- 4],LOADER2_SZ
mov edx,DISK_FLOPPY
mov eax,ldr_start
mov ebx,LOADER_CHS   ;00HHCCCS;
mov ecx,LOADER_SZ
xor si,si
call write_disk
mov dx,msg6
jc exit
mov ebx,LOADER2_CHS 
mov ecx,LOADER2_SZ
mov eax,ldr2_start
mov edx,DISK_FLOPPY
mov si,ldr_start + LOADER_SZ - MAX_CHSINTS_SZ 
mov dword [si],0
i3
call write_disk
mov dx,msg6
jc exit
mov dx,msgok
;;;;;;;;;;;;
exit:
call msg
xor ax,ax
int 16h 
int 20h

%include "procs.asm"
;;;;;;;;;;;;;data
nsct_ldr dd 0
msg1 db 'Read sect error!$'
msg2 db 'CHS overflow!$'
msg3 db 'Wrong MBR magic!$'
msg4 db 'Wrong MBR: more then 1 active partition!$'
msg5 db 'Too big loader1 !$'
msg6 db 'Write sectors error!$'
msgok db 'Ok!$'
;;; Inc files
mbr_start:
incbin 'mbr.com'
MBR_SZ equ $ - mbr_start	
;
ldr_start:
incbin 'ldr.com'
LOADER_SZ equ $ - ldr_start	
;
ldr2_start:
incbin 'ldr2.com'
LOADER2_SZ equ $ - ldr_start	
;
buf: